package com.hqyj.springBoot.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ViewMappingInterceptor implements HandlerInterceptor {

    public static final Logger LOGGER = LoggerFactory.getLogger(ViewMappingInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        LOGGER.debug("============ Pre View Mapping Interceptor ============");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           ModelAndView modelAndView) throws Exception {
        LOGGER.debug("============ Post View Mapping Interceptor ============");
        // 判断是否是页面请求，需要排除 接口请求、重定向请求、转发请求
        if (modelAndView == null ||
                modelAndView.getViewName().startsWith("redirect")||
                modelAndView.getViewName().startsWith("foward")){
            return;
        }
        // 获取请求 uri ---- /test/thymeleafTest
        String path = request.getServletPath();

        // 判断 modelmap 中是否有 template 的设置（控制器中手动设置），手动设置优先级高于自动设置
        String template = (String) modelAndView.getModelMap().get("template");
        if (StringUtils.isBlank(template)){
            // 没有手动设置，自动封装 template
            modelAndView.getModelMap().
                    addAttribute("template",path.substring(1,path.length()));
        }
        HandlerInterceptor.super.postHandle(request,response,handler,modelAndView);

    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) throws Exception {
        LOGGER.debug("============ After View Mapping Interceptor ============");

    }
}
